import React, { Component } from 'react';

class Index extends Component {
    constructor(props){
        super(props)
        this.state ={
            msg:"",
            list:[]
        }
    }
    render() {
        const ListItem =this.state.list.map((item,index)=>{
            return (<div key={item}> <span>{index+1}</span>{item} 
            <button onClick={this.handleDetail.bind(this.index)}>删除</button>
             </div>)
        })
        return (
            <div>
               <h1>todolist</h1>
               <input type="text" value={this.state.msg}
               onChange ={this.handleChange}
               onKeyUp={this.handleEnter}
               />
               {ListItem}
            </div>
        );
    }
    handleChange=(event)=>{
        console.log(event.target.value);
        this.setState({
            msg:event.target.value
        })
    }
    handleEnter=(event)=>{
       if(event.keyCode===13){
           console.log(this.state.msg);
           var list =this.state.list
           list.push(this.state.msg)
           this.setState({
               list,
               msg:""
           })
           localStorage.setItem("arr",JSON.stringify(this.state.list))
       }
    }
    handleDetail=(index)=>{
        let list =this.state.list
        list.splice(index,1)
        this.setState({
            list
        })
        localStorage.setItem("arr",JSON.stringify(this.state.list))
    }
    componentDidMount(){
        var count =localStorage.getItem('arr')
        console.log(count);   
        this.setState({
            list:JSON.parse(count)
        })
    }
   
    
}

export default Index;
